import React, { useEffect, useRef, useState } from 'react'
import {
  Card, Breadcrumb, Form, Radio, Select, Button, Input,
  Space, Upload, message, Modal
} from 'antd'
import { PlusOutlined } from '@ant-design/icons';
import styles from './index.module.scss'
import { Link, useHistory, useParams } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import { getChannelList, addArticle, editArticle, getArticleDetail } from '@/store/actions/article'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'


export default function Publish() {
  const dispatch = useDispatch()
  const formRef = useRef(null)
  const history = useHistory()
  const { id } = useParams()
  const [isVisible, setIsVisible] = useState(false)
  const [preview, setPreview] = useState('')

  // 频道-----------------
  const channelList = useSelector(state => state.article.channels)
  useEffect(() => {
    // 获取频道数据
    dispatch(getChannelList())
  }, [dispatch])

  // 封面类型-------------
  const [type, setType] = useState(1)
  // 上传封面类型change
  const onTypeChange = (e) => {
    const count = e.target.value
    setType(count)
    setFileList(fileRef.current.slice(0, count))
  }

  // 封面上传-------------
  const [fileList, setFileList] = useState([])
  const fileRef = useRef(fileList)
  // 上传change
  const uploadChange = ({ fileList }) => {
    setFileList(fileList)
    fileRef.current = fileList
    formRef.current.validateFields(['type'])
  }

  // 图片预览
  const onPreview = (file) => {
    setIsVisible(true)
    setPreview(file.url || file.response.data.url)
  }
  // 获取详情
  useEffect(() => {
    if (!id) return
    dispatch(getArticleDetail(id)).then(res => {
      formRef.current.setFieldsValue({
        ...res,
        type: res.cover.type
      })
      setType(res.cover.type)
      const list = res.cover.images.map((item) => {
        return {
          url: item
        }
      })
      setFileList(list)
      fileRef.current = list
    })
  }, [dispatch, id])
  // 表单提交
  const onFinish = (values) => {
    add(false, values)
  }

  // 保存草稿
  const handleDraft = async () => {
    const values = await formRef.current.validateFields()
    add(true, values)
  }

  // 保存接口-提取公共方法
  const add = async (draft, values) => {
    const images = fileList.map(item => {
      if (item.url) {
        return item.url
      } else {
        return item.response.data.url
      }
    })
    const params = {
      ...values,
      cover: {
        type: type,
        images
      }
    }
    if (id) {
      await dispatch(editArticle(draft, {
        ...params,
        id
      }))
    } else {
      await dispatch(addArticle(draft, params))
    }
    message.success('操作成功')
    history.push('/home/article')
  }
  return (
    <div className={styles.root}>
      <Card title={
        <Breadcrumb>
          <Breadcrumb.Item>
            <Link to="/home">首页</Link>
          </Breadcrumb.Item>
          <Breadcrumb.Item>{id ? '编辑' : '发布'}文章</Breadcrumb.Item>
        </Breadcrumb>
      }>
        <Form
          ref={formRef}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          initialValues={{
            content: '',
            type: type
          }}
          onFinish={onFinish}>
          <Form.Item
            label="标题"
            name="title"
            rules={[
              {
                required: true,
                message: '标题不能为空'
              }
            ]}>
            <Input placeholder="请输入文章的标题" style={{ width: 400 }}></Input>
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[
              {
                required: true,
                message: '频道不能为空'
              }
            ]}>
            <Select placeholder="请选择频道" style={{ width: 200 }} allowClear>
              {channelList.map(item => (
                <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            label="封面"
            name="type"
            rules={[
              {
                validator(_, value) {
                  if (fileList.length !== value) {
                    return Promise.reject(new Error(`请上传${value}张图片`))
                  } else {
                    return Promise.resolve()
                  }
                }
              }
            ]}>
            <Radio.Group value={type} onChange={onTypeChange}>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }} >
            <Upload
              listType="picture-card"
              name="image"
              action={`${process.env.REACT_APP_URL}upload`}
              fileList={fileList}
              onChange={uploadChange}
              maxCount={type}
              onPreview={onPreview}>
              {fileList.length < type && <PlusOutlined />}
            </Upload>
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[
              {
                required: true,
                message: '内容不能为空'
              }
            ]}>
            <ReactQuill ></ReactQuill>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
            <Space>
              <Button type="primary" htmlType="submit">发布文章</Button>
              <Button onClick={handleDraft}>存入草稿</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
      <Modal
        width={800}
        title="图片预览"
        footer={null}
        visible={isVisible}
        onCancel={() => setIsVisible(false)}>
        <div style={{ textAlign: 'center' }}>
          <img src={preview} style={{ width: 600 }} alt="" />
        </div>
      </Modal>
    </div>
  )
}
